"""网关用户连接管理"""


class ConnManage(object):
    def __init__(self):
        # 玩家uid链接映射
        self.uid2Conn = {}
        # 链接对象id映射
        self.id2Conn = {}

    # 新的conn链接
    async def add_conn(self, conn):
        self.id2Conn[conn.id] = conn

    # 移除一个conn
    async def remove_conn(self, conn):
        _id, _uid = conn.id, conn.uid
        if _id in self.id2Conn:
            del self.id2Conn[_id]

        if _uid in self.uid2Conn:
            del self.uid2Conn[_uid]

    # 关闭所有链接
    async def close_all_conn(self):
        for _, conn in self.id2Conn.items():
            conn.uid = None
            await self.remove_conn(conn)

    # 广播消息给所有玩家
    async def broadcast(self, msg):
        for _, conn in self.uid2Conn.items():
            await conn.send(msg)

    # 发送消息给玩家
    async def send_msg(self, uid, msg):
        _conn = self.uid2Conn.get(uid)
        if not _conn:
            return

        await _conn.send(msg)

    # 发送消息给多个玩家
    async def send_msg_by_many(self, uid_list, msg):
        for uid in uid_list:
            await self.send_msg(uid, msg)

    # 发送指定消息给指定玩家
    async def send_uid2msg(self, uid2msg):
        for uid, msg in uid2msg.items():
            await self.send_msg(uid, msg)

    # 其他用户登陆
    async def other_login(self, conn_id):
        _conn = self.id2Conn.get(conn_id)
        if not _conn:
            return

        _conn.uid = None
        await _conn.send("other_login")
        del self.id2Conn[conn_id]

    # 设置conn的uid
    def set_conn_uid(self, uid, conn):
        self.uid2Conn[uid] = conn


# 链接对象管理
connManage = ConnManage()
